package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengException;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Linzkr
 * @description: TODO 实现用户认证  也就是根据数据库查出用户信息
 * @date 2023/1/31 21:37
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService{
    @Autowired
    XcUserMapper userMapper;
    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    XcMenuMapper xcMenuMapper ;
//    根据用户名查出用户信息---UserDetails
    @Override
    public UserDetails loadUserByUsername(String authParamsDTOJSON) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(authParamsDTOJSON, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求，传入的格式无法转换为AuthParamsDTO对象");
            throw new RuntimeException(e);
        }
        String authType = authParamsDto.getAuthType();
//      动态拿到具体的实现类
        AuthService authService =  applicationContext.getBean(authType + "_auth_service",AuthService.class);
//        认证成功返回用户信息
        XcUserExt xcUserExt = authService.execute(authParamsDto);

//        认证通过
        return getUserDetails(xcUserExt);
    }
//    根据xcUserExt对象构造一个UserDetail对象
    public UserDetails getUserDetails(XcUserExt xcUserExt){
//        调用mapper 查询数据库中用户的权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUserExt.getId());
        ArrayList<String> authorityList = new ArrayList<>();

        xcMenus.forEach(xcMenu -> {
            String code = xcMenu.getCode();
            authorityList.add(code);
        });
        String[] authorities = authorityList.toArray(new String[0]);
        if (authorityList.size()==0){
            XueChengException.cast("无权限");
        }
        String jsonString = JSON.toJSONString(xcUserExt);
//        封装为JWT
        UserDetails userDetails = User.withUsername(jsonString).password("").authorities(authorities).build();
        return userDetails;


    }
}

